#include "videoroom.h"
#include "ui_videoroom.h"
#include <QThread>
#include <QShowEvent>
#include <QScreen>
#include <QGuiApplication>
#include "User.h"

#include "../main/mainwindow.h"

extern User user;
extern MsgQueue queue_send;

Videoroom::Videoroom(quint16 roomId, const QList<quint16>& partnerList, QWidget* parent)
    : roomId(roomId), QWidget(parent), partnerList(partnerList)
    , ui(new Ui::Videoroom)
{
    ui->setupUi(this);

    cameraHandler = new CameraHandler(this);
    imageHandler = new ImageHandler(this);
    audioHandler = new AudioHandler(this);

    imageHandler->init(cameraHandler);
    audioHandler->init();

    ui->tableWidget->setHorizontalHeaderLabels({"历史消息"});
    ui->tableWidget->setColumnWidth(0, 237);

    connect(ui->pushButtonSend, &QPushButton::clicked,
                 this, &Videoroom::on_pushButton_send_clicked);
    connect(ui->tableWidgetUser, &QTableWidget::cellClicked,
            this, &Videoroom::onTableCellClicked);

    setPartnerList();
}

Videoroom::~Videoroom()
{
    delete ui;
}

void Videoroom::onNewFrame(const QImage &img)
{
    // 保证在主线程更新 GUI
    if (QThread::currentThread() != qApp->thread()) {
        QMetaObject::invokeMethod(this, "onNewFrame",
                                  Qt::QueuedConnection,
                                  Q_ARG(QImage, img));
        return;
    }

    ui->label->setPixmap(QPixmap::fromImage(img));
}

void Videoroom::recvNewFrame(const QImage &img)
{
    // 保证在主线程更新 GUI
    if (QThread::currentThread() != qApp->thread()) {
        QMetaObject::invokeMethod(this, "recvNewFrame",
                                  Qt::QueuedConnection,
                                  Q_ARG(QImage, img));
        return;
    }

    ui->labelVideo->setPixmap(QPixmap::fromImage(img));
}

void Videoroom::recvNewText(const QString& text) {
    qDebug() << text;
    int row = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(row); 
    ui->tableWidget->setItem(row, 0, new QTableWidgetItem(text));
}


//窗口显示时居中
void Videoroom::showEvent(QShowEvent *event) {
    QWidget::showEvent(event);
    move(
        QGuiApplication::primaryScreen()->availableGeometry().center()
        - rect().center()
    );
}

//按下返回键
void Videoroom::on_pushButton_clicked() {
    MSG msg;
    msg.type = MSG::LEAVE;
    msg.userId = user.id;
    msg.data = QByteArray::number(roomId);
    queue_send.push_back(msg);
    emit backToMainClicked();
}

//按下聊天窗口发送消息键
void Videoroom::on_pushButton_send_clicked()
{
    QString text = ui->textEdit->toPlainText().trimmed();
    if (!text.isEmpty()){
        queue_send.push_back(MessageHelper::makeTextMessage(ui->textEdit->toPlainText().trimmed()));
        ui->textEdit->clear();
    }
}

//点击用户头像：（即tablewidgetUser的一列）
void Videoroom::onTableCellClicked(int row, int column)
{
    QTableWidgetItem *item = ui->tableWidgetUser->item(row, column);
    if (item) {
        QString text = item->text();
        qDebug() << "点击的行文本：" << text;
        // 你可以在这里做任何处理，比如复制到剪贴板等
    }
}

//工具函数：把 “头像路径” 变成 “能放进单元格的 QLabel”
static QLabel* createAvatarLabel(const QString &path,
                                 int size,
                                 QWidget *parent)
{
    QLabel *label = new QLabel(parent);
    label->setFixedSize(size, size);
    label->setAlignment(Qt::AlignCenter);

    if (QFile::exists(path)) {
        QPixmap pix(path);
        // 保持比例缩放并填满 label
        pix = pix.scaled(size, size,
                         Qt::KeepAspectRatio,
                         Qt::SmoothTransformation);
        label->setPixmap(pix);
    } else {
        label->setText("未找到\n用户头像");
        label->setWordWrap(true);
        label->setStyleSheet("color:#666;");
    }
    return label;
}

static QLabel* createLabel(int size, quint16 userId, QWidget *parent) {
    QLabel *label = new QLabel(parent);
    label->setFixedSize(size, size);
    label->setAlignment(Qt::AlignCenter);

    label->setText(QString::number(userId));
    label->setWordWrap(true);
    label->setStyleSheet("color:#666;");
    return label;
}

const int avatarSize=191;                 // 想要的头像宽度/高度
//统一设置列宽、列数，并填充头像
void Videoroom::setAvatarList(const QStringList &imgPaths)
{
    ui->tableWidgetUser->setColumnCount(imgPaths.size());

    for (int col = 0; col < imgPaths.size(); ++col) {
        QLabel *avatar = createAvatarLabel(imgPaths.at(col),
                                           avatarSize,
                                           ui->tableWidgetUser);
        ui->tableWidgetUser->setCellWidget(0, col, avatar);
        ui->tableWidgetUser->setColumnWidth(col, avatarSize);
    }
}

void Videoroom::setPartnerList() {
    ui->tableWidgetUser->setColumnCount(partnerList.size());

    for (int col = 0; col < partnerList.size(); col++) {
        QLabel *avatar = createLabel(avatarSize, partnerList.at(col), ui->tableWidgetUser);
        ui->tableWidgetUser->setCellWidget(0, col, avatar);
        ui->tableWidgetUser->setColumnWidth(col, avatarSize);
    }
}

void Videoroom::addPartner(const quint16& userId) {
    partnerList.append(userId);
    setPartnerList();
}

void Videoroom::delPartner(const quint16& userId) {
    partnerList.removeAll(userId);
    setPartnerList();
}

//初始化用户头像表格
void Videoroom::initUserAvatar(){
    this->ui->tableWidgetUser->setRowCount(1);
    this->ui->tableWidgetUser->setFixedHeight(avatarSize + 4);   // 留 2 px 边距
    this->ui->tableWidgetUser->verticalHeader()->setVisible(false);
    this->ui->tableWidgetUser->horizontalHeader()->setVisible(false);
    this->ui->tableWidgetUser->setShowGrid(false);
    this->ui->tableWidgetUser->setEditTriggers(QAbstractItemView::NoEditTriggers);
    this->ui->tableWidgetUser->setSelectionMode(QAbstractItemView::NoSelection);
}

void Videoroom::on_pushButtonVideo_clicked() {

}